import path from "path"
import { createSSRApp } from "vue"
import { renderToString } from "vue/server-renderer"
const server = require("express")()
const fs = require("fs")

server.get("/", (req, res) => {
    res.redirect("/home")
})
server.get("/**/*.js", (req, res) => {
    let jsStr = fs.readFileSync(path.resolve(__dirname, "../pages/" + req.path)).toString()
    res.end(jsStr)
})

server.get("/*", async (req, res) => {
    const requestPath = req.path
    // console.log("request----", requestPath)
    const app = createSSRApp(home)
    var obj = {}
    if (app._component.ssrAsync) {
        obj = await app._component.ssrAsync()
        app.config.globalProperties.$ssrData = obj || {}
    }
    let templateHtml = fs.readFileSync(path.resolve(__dirname, "../pages/home/index.html")).toString()
    renderToString(app).then(html => {
        templateHtml = templateHtml.replace(`<div id="app"></div>`, `<script>window.$ssrData = ${JSON.stringify(obj)}</script><div id="app">${html}</div>`)
        res.end(templateHtml)
    })
})
server.listen(8888, () => {
    console.log("服务已启动")
})